<template>
  <view class="job-detail-page">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-button" @click="goBack">
        <image class="back-icon" src="/static/back.png"></image>
      </view>
      <text class="page-title">岗位详情</text>
    </view>
    
    <!-- 可滚动内容区域 -->
    <scroll-view class="scroll-container" scroll-y="true" :style="{ height: scrollHeight + 'px' }">
      <!-- 岗位信息区域 -->
      <view class="job-info-section">
        <view class="job-info-row">
          <view class="icon-wrap">
            <image class="company-icon" :src="job.companyIcon" mode="aspectFill"></image>
          </view>
          <view class="job-info-text">
            <view class="job-title-row">
              <view class="job-title">{{ job.jobTitle }}</view>
              <button class="favorite-btn-inline" @click="toggleFavorite" @longpress="unfavoriteJob">
                <image class="favorite-icon" :src="isFavorite ? '/static/shouc.png' : '/static/shouc1.png'" mode="aspectFit"></image>
              </button>
            </view>
            <view class="company-name">{{ job.companyName }}</view>
          </view>
        </view>
        <view class="tags-row">
          <text class="tag" v-for="(tag, i) in job.tags" :key="i">{{ tag }}</text>
        </view>
        <view class="salary-location-row">
          <text class="salary">{{ job.salary || '18-42k*16' }}</text>
          <text class="location">{{ job.province || '北京' }} {{ job.city || '朝阳区' }}</text>
        </view>
      </view>

      <!-- 内容卡片 -->
      <view class="content-section">
      <!-- 岗位描述卡片 -->
      <view class="content-card">
        <view class="card-header-vertical">
          <text class="card-title">岗位描述</text>
          <view class="card-content-below">
            {{ job.jobDescription }}
          </view>
        </view>
      </view>
      
      <!-- 任职要求卡片 -->
      <view class="content-card">
        <view class="card-header-vertical">
          <text class="card-title">任职要求</text>
          <view class="card-content-below">
            {{ job.jobRequirement }}
          </view>
        </view>
      </view>
      
      <!-- 公司详情卡片 -->
      <view class="content-card company-card" @click="goToCompanyDetail">
        <view class="card-header">
          <text class="card-title">公司详情</text>
        </view>
        <view class="company-info">
          <image class="company-icon-large" :src="job.companyIcon" mode="aspectFill"></image>
          <view class="company-text">
            <text class="company-name-large">{{ job.companyName }}</text>
            <text class="company-location">{{ job.province }} {{ job.city }}</text>
          </view>
          <button class="view-company-btn" @click="goToCompanyDetail">
            <text class="view-btn-text">点击查看</text>
          </button>
        </view>
      </view>
      </view>
    </scroll-view>
    
    <!-- 加载覆盖层 -->
    <view v-if="isLoading" class="loading-mask">
      <view class="spinner"></view>
    </view>
    
    <!-- 优化后的底部操作栏 -->
    <view class="action-bar">
      <button class="ai-interview-btn" @click="goToAIInterview">
        <image class="ai-btn-icon" src="/static/user.png" mode="aspectFit"></image>
        <text class="ai-btn-text">AI面试</text>
      </button>
      <button class="apply-btn" @click="handleApply">
        <text>立即投递</text>
      </button>
    </view>
  </view>
</template>

<style scoped>
.job-detail-page {
  min-height: 100%;
  background: linear-gradient(135deg, #f0f9f4 0%, #e8f5e8 100%);
  position: relative;
}

/* 可滚动容器 */
.scroll-container {
  position: fixed;
  top: 100px;
  left: 0;
  right: 0;
  bottom: 80px; /* 减少底部边距，给内容更多显示空间 */
  z-index: 5;
  background: transparent;
  overflow-y: auto; /* 确保垂直滚动 */
  -webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
}

/* 内容区域 */
.content-section {
  padding: 0 24rpx 120rpx 24rpx; /* 增加底部内边距，防止被底部操作栏遮挡 */
}

/* 岗位信息区域在滚动容器内 */
.job-info-section {
  background: transparent;
  border-radius: 0;
  margin: 0;
  padding: 24rpx 36rpx 40rpx;
  position: relative;
  z-index: 5;
}

.job-detail-page::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 80%, rgba(34, 197, 94, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(16, 185, 129, 0.05) 0%, transparent 50%);
  pointer-events: none;
  z-index: 0;
}

/* 顶部导航 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #f0f9f4 0%, #e8f5e8 100%);
  padding: 100rpx 36rpx 40rpx;
  color: #333333;
  border-bottom-left-radius: 32rpx;
  border-bottom-right-radius: 32rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.back-button {
  position: absolute;
  top: 98rpx;
  left: 36rpx;
  z-index: 10;
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(16, 185, 129, 0.15);
  border-radius: 32rpx;
  transition: all 0.3s ease;
  border: 1rpx solid rgba(16, 185, 129, 0.2);
}

.back-icon {
  width: 36rpx;
  height: 36rpx;
  opacity: 0.8;
  transition: opacity 0.3s ease;
  filter: brightness(0);
}

.back-icon:active {
  opacity: 1;
}

.page-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #000000;
  text-align: center;
  flex: 1;
}



.job-info-row {
  margin-bottom: 24rpx;
}



.icon-wrap {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  background: transparent;
  padding: 0;
}

.company-icon {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  object-fit: cover;
}

.job-info-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 16rpx;
}

.job-title-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.job-info-text {
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1;
  min-width: 0;
}

.job-title {
  color: #222;
  font-size: 36rpx;
  font-weight: 700;
  margin-bottom: 6rpx;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.ai-interview-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: #ffffff;
  font-weight: 700;
  box-shadow: 0 6rpx 20rpx rgba(16, 185, 129, 0.3);
}

.ai-interview-btn:active {
  transform: translateY(0);
  box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.5);
}

.ai-btn-text {
  margin-right: 8rpx;
}

.ai-btn-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.favorite-btn-inline {
  background: transparent;
  border: none;
  outline: none;
  padding: 8rpx;
  transition: all 0.3s ease;
  margin-left: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64rpx;
  height: 64rpx;
}

.favorite-btn-inline::after {
  border: none;
}

.favorite-btn-inline:active {
  transform: translateY(0);
  box-shadow: 0 2rpx 6rpx rgba(16, 185, 129, 0.3);
}

.favorite-icon {
  width: 40rpx;
  height: 40rpx;
}

.company-name {
  color: #666;
  font-size: 26rpx;
  margin-bottom: 0;
  text-align: left;
}

.tags-row {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  margin: 8rpx 0;
  flex-wrap: wrap;
  gap: 8rpx;
}

.tag {
  background: rgba(16, 185, 129, 0.1);
  color: #10b981;
  font-size: 22rpx;
  border-radius: 16rpx;
  padding: 6rpx 12rpx;
  margin-right: 8rpx;
  border: 1rpx solid rgba(16, 185, 129, 0.2);
  font-weight: bold;
}

.salary-location-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 16rpx;
}

.salary {
  color: #10b981;
  font-size: 32rpx;
  font-weight: 700;
}

.location {
  color: #6b7280;
  font-size: 26rpx;
}



.content-card {
  background: #ffffff;
  border-radius: 20rpx;
  margin: 0 24rpx 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  border: 1rpx solid rgba(16, 185, 129, 0.08);
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.content-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4rpx;
  background: linear-gradient(90deg, #10b981 0%, #059669 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.card-header {
  padding: 28rpx 24rpx 20rpx;
  border-bottom: 1rpx solid rgba(16, 185, 129, 0.08);
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.03) 0%, rgba(16, 185, 129, 0.01) 100%);
  position: relative;
  flex-direction: row;
}

.card-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #10b981;
  position: relative;
}

.card-title::after {
  content: '';
  position: absolute;
  bottom: -6rpx;
  left: 0;
  width: 24rpx;
  height: 2rpx;
  background: linear-gradient(90deg, #10b981 0%, #059669 100%);
  border-radius: 1rpx;
}

.card-header-vertical {
  padding: 28rpx 24rpx 20rpx;
  border-bottom: 1rpx solid rgba(16, 185, 129, 0.08);
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.03) 0%, rgba(16, 185, 129, 0.01) 100%);
  position: relative;
}

.card-content-below {
  padding: 16rpx 0 0 0;
  font-size: 26rpx;
  color: #4a5568;
  line-height: 1.7;
  text-align: left;
  text-indent: 0;
}

/* 卡片进入动画已移除 */

/* 简化加载动画 */
.spinner {
  width: 56rpx;
  height: 56rpx;
  border: 4rpx solid rgba(16, 185, 129, 0.1);
  border-top-color: #10b981;
  border-radius: 32rpx;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 加载遮罩 */
.loading-mask {
  background: rgba(255, 255, 255, 0.8);
}

/* 优化后的底部操作栏样式 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: row;
  height: 160rpx;
  background: transparent;
  z-index: 100;
  padding: 16rpx 24rpx;
  align-items: center;
  gap: 12rpx;
}

.ai-interview-btn, .apply-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 24rpx;
  height: 72rpx;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}


.apply-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: #ffffff;
  font-weight: 700;
  box-shadow: 0 6rpx 20rpx rgba(16, 185, 129, 0.3);
}

.apply-btn:active {
  transform: translateY(0);
  box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.5);
}

/* 公司详情卡片样式 */
.company-card .card-header {
	flex-direction: row;
  border-bottom: none;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.03) 0%, rgba(16, 185, 129, 0.01) 100%);
}

.company-card .company-info {
  flex-direction: row;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.03) 0%, rgba(16, 185, 129, 0.01) 100%);
  border-radius: 12rpx;
  margin: 0 24rpx 20rpx;
  border: 1rpx solid rgba(16, 185, 129, 0.08);
  transition: all 0.3s ease;
}

.company-icon-large {
  width: 72rpx;
  height: 72rpx;
  border-radius: 12rpx;
  margin-right: 16rpx;
}

.company-text {
  flex: 1;
}

.company-name-large {
  font-size: 32rpx;
  font-weight: 700;
  color: #10b981;
  display: flex;
  margin-bottom: 8rpx;
}

.company-location {
  font-size: 26rpx;
  color: #6b7280;
}

/* 查看公司按钮样式 */
.view-company-btn {
  background: rgba(255, 255, 255, 0.9);
  border: 1rpx solid rgba(16, 185, 129, 0.2);
  border-radius: 18rpx;
  padding: 10rpx 20rpx;
  margin-left: 12rpx;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 110rpx;
  height: 52rpx;
  box-shadow: 0 8rpx 32rpx rgba(16, 185, 129, 0.1);
  position: relative;
  overflow: hidden;
}

.view-company-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, 
    rgba(16, 185, 129, 0.1) 0%, 
    rgba(16, 185, 129, 0.05) 50%, 
    rgba(16, 185, 129, 0.1) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.view-company-btn:active {
  transform: translateY(0) scale(0.98);
  background: rgba(255, 255, 255, 0.25);
  box-shadow: 
    0 4rpx 20rpx rgba(16, 185, 129, 0.2),
    inset 0 1rpx 0 rgba(255, 255, 255, 0.5),
    inset 0 -1rpx 0 rgba(16, 185, 129, 0.2);
}

.view-btn-text {
  color: #10b981;
  font-size: 22rpx;
  font-weight: 600;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.company-description {
  padding: 0 24rpx 24rpx;
  font-size: 26rpx;
  color: #6b7280;
  line-height: 1.6;
}

.arrow-icon {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.08) 0%, rgba(16, 185, 129, 0.04) 100%);
  border-radius: 32rpx;
  border: 1rpx solid rgba(16, 185, 129, 0.12);
  transition: all 0.3s ease;
}

.arrow {
  font-size: 28rpx;
  color: #10b981;
  font-weight: bold;
}


</style>

<script>
export default {
  data() {
    return {
      isLoading: true,
      error: null,
      job: {},
      tabActive: 0,
      id: '',
      isFavorite: false,
      scrollTop: 0,
      backIcon: '/static/back.png',
      topBg: '/static/BG.png',
      apiUrl: 'https://api.example.com/job-detail',
      scrollIntoView: '',
      mainContentMarginTop: 0,
      scrollHeight: 0
    }
  },
  onReady() {
    this.calculateScrollHeight();
  },
  onLoad(options) {
    this.id = options.id || '';
    this.fetchJobDetail();
    // 检查收藏状态
    this.checkFavoriteStatus();
  },
  methods: {
    calculateScrollHeight() {
      const sysInfo = uni.getSystemInfoSync();
      
      // 计算滚动区域高度：屏幕高度 - 顶部导航高度 - 底部操作栏高度
      const headerHeight = 100; // 顶部导航高度 (CSS中设置的top: 100px)
      const actionBarHeight = 80; // 底部操作栏高度(CSS中设置的bottom: 80px)
      
      this.scrollHeight = sysInfo.windowHeight - headerHeight - actionBarHeight;
    },
    goBack() {
      uni.navigateBack();
    },
    goToCompanyDetail() {
      if (this.job.companyId) {
        uni.navigateTo({
          url: `/pages/company-detail/index?id=${this.job.companyId}`
        });
      } else {
        uni.showToast({
          title: '公司信息暂未开放',
          icon: 'none'
        });
      }
    },

    goToAIInterview() {
      uni.showModal({
        title: 'AI面试',
        content: '即将为您开启AI面试功能，是否继续？',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: `/pages/ai-chat/index?jobId=${this.id}&jobTitle=${this.job.jobTitle}`
            });
          }
        }
      });
    },

    async fetchJobDetail() {
      this.isLoading = true;
      this.error = null;
      try {
        // 真实接口请求，返回结构需与mock一致
        const res = await uni.request({
          url: `${this.apiUrl}?id=${this.id}`,
          method: 'GET'
        });
        if (res[1] && res[1].statusCode === 200 && res[1].data) {
          this.job = res[1].data;
        } else {
          throw new Error('加载失败');
        }
      } catch (e) {
        // 请求失败时回退到mock数据
        const mockJob = {
          id: 'job1',
          companyId: 'company1',
          companyIcon: 'https://img1.baidu.com/it/u=1739539544,3582138974&fm=253&fmt=auto&app=120&f=PNG?w=243&h=243',
          jobTitle: '用户产品经理',
          companyName: '小红书',
          salary: '18-42k*16',
          province: '北京',
          city: '朝阳区',
          tags: ['2025届', '商业化', '社交产品', '高薪岗位'],
          jobDescription: 'We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more? We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more?',
          jobRequirement: 'We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more?We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more?We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more?We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more?',
          companyDetail: 'We are the teams who create all of Facebook\'s products used by billions of people around the world. Want to build new features and improve existing products like Messenger, Video, Groups, News Feed, Search and more?'
        };
        this.job = mockJob;
      } finally {
        this.isLoading = false;
      }
    },
    scrollToSection(id, idx) {
      this.scrollIntoView = id;
      this.tabActive = idx;
    },
    onContentScroll(e) {
      this.scrollTop = e.detail.scrollTop;
      
      uni.createSelectorQuery().in(this).selectAll('.card-section .content-card').boundingClientRect(rects => {
        const scrollTop = e.detail.scrollTop;
        let active = 0;
        for (let i = 0; i < rects.length; i++) {
          if (scrollTop + 120 >= rects[i].top) active = i;
        }
        this.tabActive = active;
      }).exec();
    },
    toggleFavorite() {
      if (this.isFavorite) {
        // 如果已收藏，取消收藏
        this.isFavorite = false;
        // 从本地存储中移除收藏
        this.removeFromFavorites();
        uni.showToast({
          title: '已取消收藏',
          icon: 'success'
        });
        
        // TODO: 调用取消收藏接口
        // try {
        //   await uni.request({
        //     url: `/api/jobs/${this.id}/favorite`,
        //     method: 'DELETE'
        //   })
        // } catch (error) {
        //   console.error('取消收藏失败:', error)
        // }
      } else {
        // 如果未收藏，添加到收藏
        this.isFavorite = true;
        // 添加到本地存储
        this.addToFavorites();
        uni.showToast({
          title: '已添加到我的收藏',
          icon: 'success'
        });
        
        // TODO: 调用收藏接口
        // try {
        //   await uni.request({
        //     url: `/api/jobs/${this.id}/favorite`,
        //     method: 'POST'
        //   })
        // } catch (error) {
        //   console.error('收藏操作失败:', error)
        // }
      }
    },

    unfavoriteJob() {
      if (this.isFavorite) {
        // 取消收藏
        this.isFavorite = false;
        this.removeFromFavorites();
        uni.showToast({
          title: '已取消收藏',
          icon: 'success'
        });
        
        // TODO: 调用取消收藏接口
        // try {
        //   await uni.request({
        //     url: `/api/jobs/${this.id}/favorite`,
        //     method: 'DELETE'
        //   })
        // } catch (error) {
        //   console.error('取消收藏失败:', error)
        // }
      }
    },

    // 添加到收藏列表
    addToFavorites() {
      try {
        const favorites = uni.getStorageSync('favoriteJobs') || [];
        const jobData = {
          id: this.id,
          jobTitle: this.job.jobTitle,
          companyName: this.job.companyName,
          companyIcon: this.job.companyIcon,
          salary: this.job.salary,
          province: this.job.province,
          city: this.job.city,
          tags: this.job.tags,
          addTime: new Date().getTime()
        };
        
        // 检查是否已经存在
        const existingIndex = favorites.findIndex(item => item.id === this.id);
        if (existingIndex === -1) {
          favorites.unshift(jobData); // 添加到列表开头
          uni.setStorageSync('favoriteJobs', favorites);
        }
      } catch (error) {
        console.error('保存收藏失败:', error);
      }
    },

    // 从收藏列表移除
    removeFromFavorites() {
      try {
        const favorites = uni.getStorageSync('favoriteJobs') || [];
        const filteredFavorites = favorites.filter(item => item.id !== this.id);
        uni.setStorageSync('favoriteJobs', filteredFavorites);
      } catch (error) {
        console.error('移除收藏失败:', error);
      }
    },

    // 检查收藏状态
    checkFavoriteStatus() {
      try {
        const favorites = uni.getStorageSync('favoriteJobs') || [];
        this.isFavorite = favorites.some(item => item.id === this.id);
      } catch (error) {
        console.error('检查收藏状态失败', error);
        this.isFavorite = false;
      }
    },
    
    handleApply() {
      uni.showModal({
        title: '确认投递',
        content: '确定要投递这个岗位吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '投递成功',
              icon: 'success'
            });
            
            // TODO: 调用投递接口
            // try {
            //   await uni.request({
            //     url: `/api/jobs/${this.id}/apply`,
            //     method: 'POST'
            //   })
            // } catch (error) {
            //   console.error('投递失败', error)
            // }
          }
        }
      });
    }
  }
}
</script>
